//
//  JDMainScreenCell.swift
//  DragonWallet
//
//  Created by volantPig on 2024/3/1.
//

import UIKit
import HXPhotoPicker

class JDMainScreenCell: UITableViewCell {

    var recruitModel: JDRecruitModel? {
        didSet {
            self.refreshData()
        }
    }
    
    var playVideoVC: JDPlayVideoOrPictureViewController?
    
    private var containerView: UIView?
    var contentLabel: UILabel?
    
    var playImgV: UIImageView?
    var videoButton: UIButton?
    var imgVOne: UIButton?
    var imgVTwo: UIButton?
    var imgVThree: UIButton?
    
    var middleLine: UIView?
    
    var authorInfoLabel: UILabel?
    var callAuthorButton: UIButton?
    var addDragonUnion: UIButton?
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.contentView.backgroundColor = color("#F5F6F8")
        self.setupUIElements()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUIElements() {
        
        for subV in self.contentView.subviews {
            subV.removeFromSuperview()
        }

        self.containerView = UIView()
        self.contentView.addSubview(self.containerView!)
        self.containerView?.snp.makeConstraints({ make in
            make.left.equalTo(self.contentView).offset(12)
            make.right.equalTo(self.contentView).offset(-12)
            make.top.equalTo(self.contentView)
            make.bottom.equalTo(self.contentView).offset(-10)
        })
        self.containerView?.layer.cornerRadius = 8
        self.containerView?.backgroundColor = .white
        
        self.contentLabel = UILabel()
        self.containerView?.addSubview(self.contentLabel!)
        self.contentLabel?.snp.makeConstraints({ make in
            make.left.equalTo(self.containerView!).offset(16)
            make.right.equalTo(self.containerView!).offset(-16)
            make.top.equalTo(self.containerView!).offset(10)
        })
        self.contentLabel?.numberOfLines = 0
        self.contentLabel?.font = UIFont.systemFont(ofSize: 16, weight: .regular)
        self.contentLabel?.textColor = color("#333333")
        self.contentLabel?.text = "优质公建出租出售配套设施齐全，地角好，通!优质公建出租出售配套设施齐全，地角好，通!优质公建出租出售配套设施齐全，地角好，通!优质公建出租出售配套设施齐全，地角好，通!"

        self.videoButton = UIButton(type: .custom)
        self.containerView?.addSubview(self.videoButton!)
        self.videoButton?.snp.makeConstraints({ make in
            make.top.equalTo(self.contentLabel!.snp.bottom).offset(15)
            make.left.equalTo(self.containerView!).offset(16)
            make.size.equalTo(CGSize(width: (screenWidth-24-32-22)/3.0, height: (screenWidth-24-32-22)/3.0))
        })
        self.videoButton?.backgroundColor = .green
        self.videoButton?.addTarget(self, action: #selector(playVideo), for: .touchUpInside)
        
        self.playImgV = UIImageView()
        self.videoButton?.addSubview(self.playImgV!)
        self.playImgV?.isUserInteractionEnabled = false
        self.playImgV?.snp.makeConstraints({ make in
            make.centerX.centerY.equalTo(self.videoButton!)
        })
        self.playImgV?.image = UIImage(named: "play_button")?.withRenderingMode(.alwaysOriginal)
        
        self.imgVOne = UIButton(type: .custom)
        self.imgVOne?.addTarget(self, action: #selector(showImage(_:)), for: .touchUpInside)
        self.containerView?.addSubview(self.imgVOne!)
        self.imgVOne?.snp.makeConstraints({ make in
        })
        self.imgVOne?.isHidden = true
        self.imgVTwo = UIButton(type: .custom)
        self.imgVTwo?.addTarget(self, action: #selector(showImage(_:)), for: .touchUpInside)
        self.containerView?.addSubview(self.imgVTwo!)
        self.imgVTwo?.snp.makeConstraints({ make in
        })
        self.imgVTwo?.isHidden = true
        self.imgVThree = UIButton(type: .custom)
        self.imgVThree?.addTarget(self, action: #selector(showImage(_:)), for: .touchUpInside)
        self.containerView?.addSubview(self.imgVThree!)
        self.imgVThree?.snp.makeConstraints({ make in
        })
        self.imgVThree?.isHidden = true

        self.middleLine = UIView()
        self.containerView?.addSubview(self.middleLine!)
        self.middleLine?.snp.makeConstraints { make in
            make.left.equalTo(self.containerView!).offset(12)
            make.right.equalTo(self.containerView!).offset(-12)
            make.top.equalTo(self.videoButton!.snp.bottom).offset(10)
            make.height.equalTo(1)
        }
        self.middleLine?.backgroundColor = color("#EEEEEE")
        
        self.authorInfoLabel = UILabel()
        self.containerView?.addSubview(self.authorInfoLabel!)
        self.authorInfoLabel?.snp.makeConstraints({ make in
            make.left.equalTo(self.containerView!).offset(16)
            make.top.equalTo(self.middleLine!.snp.bottom)
            make.height.equalTo(50)
            make.bottom.equalTo(self.containerView!)
        })
        self.authorInfoLabel?.text = "联系人：迟先生"
        self.authorInfoLabel?.textColor = color("#333333")
        self.authorInfoLabel?.font = UIFont.systemFont(ofSize: 14, weight: .regular)
    
        self.callAuthorButton = UIButton(type: .custom)
        self.containerView?.addSubview(self.callAuthorButton!)
        self.callAuthorButton?.snp.makeConstraints({ make in
            make.left.equalTo(self.authorInfoLabel!.snp.right).offset(19)
            make.centerY.equalTo(self.authorInfoLabel!)
            make.size.equalTo(CGSize(width: 21, height: 21))
        })
        self.callAuthorButton?.setImage(UIImage(named: "call_image")?.withRenderingMode(.alwaysOriginal), for: .normal)
        self.callAuthorButton?.addTarget(self, action: #selector(callAuthorAction), for: .touchUpInside)
        
        self.addDragonUnion = UIButton(type: .custom)
        self.containerView?.addSubview(self.addDragonUnion!)
        self.addDragonUnion?.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 7)
        self.addDragonUnion?.titleEdgeInsets = UIEdgeInsets(top: 0, left: 7, bottom: 0, right: 0)
        self.addDragonUnion?.snp.makeConstraints({ make in
            make.right.equalTo(self.containerView!).offset(-12)
            make.centerY.equalTo(self.callAuthorButton!)
            make.width.equalTo(89)
        })
        self.addDragonUnion?.setTitle("邀加尨商圈", for: .normal)
        self.addDragonUnion?.setImage(UIImage(named: "add_DragonUnion"), for: .normal)
        self.addDragonUnion?.titleLabel?.font = UIFont.systemFont(ofSize: 13, weight: .regular)
        self.addDragonUnion?.setTitleColor(color("#333333"), for: .normal)
        self.addDragonUnion?.addTarget(self, action: #selector(addDragonUnionAction), for: .touchUpInside)
    }
    
    @objc func callAuthorAction() {
        printLog("打电话\(self.recruitModel?.mobile)")
        
        let callStr = String.init(format: "tel:%@", self.recruitModel?.mobile ?? "")
        if let callUrl = URL(string: callStr) {
            UIApplication.shared.open(callUrl, options: [:]) { isSuccess in
            }
        }
    }
    
    @objc func addDragonUnionAction() {
        if !JDTools.checkToken() {
            return
        }
        let popupConfirmView = JDPopupConfirmView()
        popupConfirmView.confirmButtonSelected = { [weak self] in
            
            
            var params = [String: Any]()
            
            params["userId"] = self?.recruitModel?.publishUserId
            
            JDNetWorkRequest(.addDragonUnion(params)) { responseStr in
                
                let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
                if commonModel?.code == "0" {
                    
                    JDSingle.default.needRefreshDragonCityUnion = true
                    
                    // 成功
//                    self?.toast(message: "邀请成功")
//                    NotificationCenter.default.post(name: NSNotification.Name.init("addDragonUnionSuccess"), object: nil)
                    JDTools.getKeyWindows()?.rootViewController?.view.toast(message: "邀请成功")
                    self?.changeaddDragonUnionState()
                } else {
                    JDTools.getKeyWindows()?.rootViewController?.view.toast(message: String.init(format: "%@", commonModel?.msg ?? ""))
                }
                
//            邀请加入龙商圈成功:{"returnMsg":"已邀请加入龙商圈","returnCode":"00","body":null}
                printLog("邀请加入龙商圈成功:\(responseStr)")
                
            } failure: { error in
                
                printLog("邀请加入龙商圈失败:\(error)")
                self?.toast(message: String.init(format: "%@", error.errorDescription ?? ""))
                
            } error: { errorCode in
                
                printLog("邀请加入龙商圈错误:\(errorCode)")
                self?.toast(message: String.init(format: "错误代码:%zd", errorCode))
            }

        }
        popupConfirmView.titleStr = String.init(format: "确定邀请 %@ 加入尨商圈吗？", self.recruitModel?.contactName ?? "")
        JDTools.getKeyWindows()?.rootViewController?.view.addSubview(popupConfirmView)
    }
    
    func changeaddDragonUnionState() {
        self.addDragonUnion?.setImage(nil, for: .normal)
        self.addDragonUnion?.setTitle("已加入尨商圈", for: .normal)
        
        guard let confirmModel = self.recruitModel else { return }
        confirmModel.hadJoined = true
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    func refreshData() {
        guard let confirmModel = self.recruitModel else { return }
        
//        self.imgVOne?.kf.setImage(with: URL(string: JDImageBaseUrl + (confirmModel.picUrl1 ?? "")))
        self.contentLabel?.text = confirmModel.content
        self.authorInfoLabel?.text = "联系人：" + (confirmModel.contactName ?? "")
        
        if confirmModel.hadJoined ?? false {
          // 已加入
            self.addDragonUnion?.setImage(nil, for: .normal)
            self.addDragonUnion?.setTitle("已加入尨商圈", for: .normal)
        } else {
            self.addDragonUnion?.setImage(UIImage(named: "add_DragonUnion"), for: .normal)
            self.addDragonUnion?.setTitle("邀加尨商圈", for: .normal)
        }
        
        if confirmModel.publishUserId == JDLoginModel.default.userId {
            self.addDragonUnion?.isHidden = true
        } else {
            self.addDragonUnion?.isHidden = false
        }
        
        self.updateCustomConstraints(confirmModel)
    }
    
    /// 更新自定义的部分空间的约束
    func updateCustomConstraints(_ currentModel: JDRecruitModel) {
            
        self.videoButton?.isHidden = true
        self.imgVOne?.isHidden = true
        self.imgVOne?.setImage(UIImage(named: "loading_placeholder")?.withRenderingMode(.alwaysOriginal), for: .normal)
        self.imgVTwo?.isHidden = true
        self.imgVTwo?.setImage(UIImage(named: "loading_placeholder")?.withRenderingMode(.alwaysOriginal), for: .normal)
        self.imgVThree?.isHidden = true
        self.imgVThree?.setImage(UIImage(named: "loading_placeholder")?.withRenderingMode(.alwaysOriginal), for: .normal)
        
        if (currentModel.videoUrl?.count ?? 0) > 0 {
            // 有视频
            self.videoButton?.isHidden = false
            self.videoButton?.backgroundColor = .purple
            self.videoButton?.setImage(JDTools.getVideoThumbnail(url: URL(string: currentModel.videoUrl ?? "")!), for: .normal)
//            self.videoButton?.setImage(JDTools.getVideoThumbnail(url: URL(string: "http://vjs.zencdn.net/v/oceans.mp4")!), for: .normal)
            self.videoButton?.snp.remakeConstraints({ make in
                make.top.equalTo(self.contentLabel!.snp.bottom).offset(15)
                make.left.equalTo(self.containerView!).offset(16)
                make.size.equalTo(CGSize(width: (screenWidth-24-32-22)/3.0, height: (screenWidth-24-32-22)/3.0))
            })
            
            if (currentModel.picUrl1?.count ?? 0) > 0 {
                self.imgVOne?.isHidden = false
                if currentModel.picUrl1?.hasPrefix("http") ?? false  {
                    self.imgVOne?.kf.setImage(with: URL(string: (currentModel.picUrl1 ?? "")), for: .normal)
                } else {
                    self.imgVOne?.downloadImage(currentModel.picUrl1 ?? "")
                }
                
                self.imgVOne?.snp.remakeConstraints({ make in
//                    make.left.equalTo(self.videoButton!.snp.right).offset(11)
                    make.left.equalTo(self.containerView!).offset(16+(screenWidth-24-32-22)/3.0+11)
//                    make.centerY.equalTo(self.videoButton!)
                    make.top.equalTo(self.contentLabel!.snp.bottom).offset(15)
                    make.size.equalTo(CGSize(width: (screenWidth-24-32-22)/3.0, height: (screenWidth-24-32-22)/3.0))
                })
            }
            
            if (currentModel.picUrl2?.count ?? 0) > 0 {
                self.imgVTwo?.isHidden = false
                if currentModel.picUrl2?.hasPrefix("http") ?? false  {
                    self.imgVTwo?.kf.setImage(with: URL(string: (currentModel.picUrl2 ?? "")), for: .normal)
                } else {
                    self.imgVTwo?.downloadImage(currentModel.picUrl2 ?? "")
                }
                
                self.imgVTwo?.snp.remakeConstraints({ make in
//                    make.left.equalTo(self.imgVOne!.snp.right).offset(11)
                    make.left.equalTo(self.containerView!).offset(16+(screenWidth-24-32-22)/3.0*2+11*2)
                    make.top.equalTo(self.contentLabel!.snp.bottom).offset(15)
                    make.size.equalTo(CGSize(width: (screenWidth-24-32-22)/3.0, height: (screenWidth-24-32-22)/3.0))
                })
            }
            
            if (currentModel.picUrl3?.count ?? 0) > 0 {
                self.imgVThree?.isHidden = false
                if currentModel.picUrl3?.hasPrefix("http") ?? false  {
                    self.imgVThree?.kf.setImage(with: URL(string: (currentModel.picUrl3 ?? "")), for: .normal)
                } else {
                    self.imgVThree?.downloadImage(currentModel.picUrl3 ?? "")
                }
                
                self.imgVThree?.snp.remakeConstraints({ make in
                    make.top.equalTo(self.videoButton!.snp.bottom).offset(11)
//                    make.centerX.equalTo(self.videoButton!)
                    make.left.equalTo(self.containerView!).offset(16)
                    make.size.equalTo(CGSize(width: (screenWidth-24-32-22)/3.0, height: (screenWidth-24-32-22)/3.0))
                })
                
                self.middleLine?.snp.remakeConstraints({ make in
                    make.left.equalTo(self.containerView!).offset(12)
                    make.right.equalTo(self.containerView!).offset(-12)
                    make.top.equalTo(self.imgVThree!.snp.bottom).offset(10)
                    make.height.equalTo(1)
                })
            }
            
        } else {
            // 无视频
            self.videoButton?.isHidden = true
            
            if (currentModel.picUrl1?.count ?? 0) > 0 {
                self.imgVOne?.isHidden = false
                if currentModel.picUrl1?.hasPrefix("http") ?? false  {
                    self.imgVOne?.kf.setImage(with: URL(string: (currentModel.picUrl1 ?? "")), for: .normal)
                } else {
                    self.imgVOne?.downloadImage(currentModel.picUrl1 ?? "")
                }
                
                self.imgVOne?.snp.remakeConstraints({ make in
                    make.top.equalTo(self.contentLabel!.snp.bottom).offset(15)
                    make.left.equalTo(self.containerView!).offset(16)
                    make.size.equalTo(CGSize(width: (screenWidth-24-32-22)/3.0, height: (screenWidth-24-32-22)/3.0))
                })
            }
            
            if (currentModel.picUrl2?.count ?? 0) > 0 {
                self.imgVTwo?.isHidden = false
                if currentModel.picUrl2?.hasPrefix("http") ?? false  {
                    self.imgVTwo?.kf.setImage(with: URL(string: (currentModel.picUrl2 ?? "")), for: .normal)
                } else {
                    self.imgVTwo?.downloadImage(currentModel.picUrl2 ?? "")
                }
                
                self.imgVTwo?.snp.remakeConstraints({ make in
                    make.top.equalTo(self.contentLabel!.snp.bottom).offset(15)
//                    make.left.equalTo(self.imgVOne!.snp.right).offset(11)
                    make.left.equalTo(containerView!).offset(16+(screenWidth-24-32-22)/3.0+11)
                    make.size.equalTo(CGSize(width: (screenWidth-24-32-22)/3.0, height: (screenWidth-24-32-22)/3.0))
                })
            }
            
            if (currentModel.picUrl3?.count ?? 0) > 0 {
                self.imgVThree?.isHidden = false
                if currentModel.picUrl3?.hasPrefix("http") ?? false  {
                    self.imgVThree?.kf.setImage(with: URL(string: (currentModel.picUrl3 ?? "")), for: .normal)
                } else {
                    self.imgVThree?.downloadImage(currentModel.picUrl3 ?? "")
                }
                
                self.imgVThree?.snp.remakeConstraints({ make in
                    make.top.equalTo(self.contentLabel!.snp.bottom).offset(15)
//                    make.left.equalTo(self.imgVTwo!.snp.right).offset(11)
                    make.left.equalTo(containerView!).offset(16+(screenWidth-24-32-22)/3.0*2+11*2)
                    make.size.equalTo(CGSize(width: (screenWidth-24-32-22)/3.0, height: (screenWidth-24-32-22)/3.0))
                })
            }
        }
    }
    
    @objc func playVideo() {
        
        self.playVideoVC = JDPlayVideoOrPictureViewController()
        self.playVideoVC?.playType = .video
        self.playVideoVC?.videoDataSource = [self.recruitModel?.videoUrl ?? ""]
        JDTools.getKeyWindows()?.addSubview(self.playVideoVC!.view)
    }
    
    @objc func showImage(_ button: UIButton) {
        let style: UIModalPresentationStyle = .custom
        var config = HXPhotoPicker.PhotoBrowser.Configuration()
        config.showDelete = false
            config.modalPresentationStyle = style
        
        /// 显示图片浏览器
        /// - Parameters:
        ///   - previewAssets: 对应 PhotoAsset 的数组
        ///   - pageIndex: 当前预览的位置
        ///   - config: 相关配置
        ///   - fromVC: 来源控制器
        ///   - transitionalImage: 初始转场动画时展示的 UIImage
        ///   - transitionHandler: 转场过渡
        ///   - deleteAssetHandler: 删除资源
        ///   - longPressHandler: 长按事件
        /// - Returns: 对应的 PhotoBrowser
        
        guard let currentImg = button.imageView?.image else { return }
        HXPhotoPicker.PhotoBrowser.show([PhotoAsset.init(localImageAsset: LocalImageAsset.init(currentImg))], pageIndex: 0, config: config, fromVC: nil, transitionalImage: nil, transitionHandler: nil, transitionCompletion: nil, deleteAssetHandler: nil, longPressHandler: nil)
        
        
//        HXPhotoPicker.PhotoBrowser.show([PhotoAsset.init(networkImageAsset: NetworkImageAsset.init(thumbnailURL: URL(string: "https://ww1.sinaimg.cn/mw690/717076a7gy1hse09y4a0pj21jk2bcqms.jpg"), originalURL: URL(string: "https://ww1.sinaimg.cn/mw690/717076a7gy1hse09y4a0pj21jk2bcqms.jpg")))], pageIndex: 0, config: config, fromVC: nil, transitionalImage: nil, transitionHandler: nil, transitionCompletion: nil, deleteAssetHandler: nil, longPressHandler: nil)
    }
    
    
}
